package com.uphone.kingmall.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.blankj.utilcode.util.LogUtils;
import com.china.zhuoyue.R;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.uphone.kingmall.adapter.CricleHomeAdapter;
import com.uphone.kingmall.adapter.CricleMenuMenuAdapter;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.CircleShopsListBean;
import com.uphone.kingmall.bean.UserShopTypeBean;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.DialogUtil;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.SharedPreferencesHelper;
import com.uphone.kingmall.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * <pre>
 *     author : radish
 *     e-mail : 15703379121@163.com
 *     time   : 2019/3/27
 *     desc   :
 * </pre>
 */
public class CricleMoreActivity extends BaseActivity implements AMapLocationListener {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_sousuo)
    ImageView ivSousuo;
    @BindView(R.id.rl_sousuo)
    RelativeLayout rlSousuo;
    @BindView(R.id.lv_menu)
    ListView lvMenu;
    @BindView(R.id.lv_home)
    GridView lvHome;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private CricleHomeAdapter homeAdapter;
    private CricleMenuMenuAdapter menuAdapter;
    private List<Integer> showTitle = new ArrayList<>();
    private List<UserShopTypeBean.ShopCatsBean> shopCats;
    private List<CircleShopsListBean.DataBean> dataList;
    private int currentId = -1;
    private int currentItem;
    private String city = "";

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_cricle_more;
    }

    @Override
    public void initView() {
        loadPermission();
        ivBack.setVisibility(View.VISIBLE);

        homeAdapter = new CricleHomeAdapter(this, dataList);
        lvHome.setAdapter(homeAdapter);
        menuAdapter = new CricleMenuMenuAdapter(this, shopCats);
        lvMenu.setAdapter(menuAdapter);
        listener();
    }

    private void listener() {


        lvMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                menuAdapter.setSelectItem(position);
                menuAdapter.notifyDataSetInvalidated();
                loadHomeData(shopCats.get(position).getId(), 1);
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                loadHomeData(currentId, 1);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                loadHomeData(currentId, ++page);
            }
        });

        lvHome.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CommonUtil.startIntent(CricleMoreActivity.this, ShopDetailActivity.class, dataList.get(position).getShopId());
            }
        });
    }

    @Override
    public void initData() {

        OkGoUtils.normalRequest(MyUrl.getShopCats, null, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    UserShopTypeBean bean = GsonUtils.getGson().fromJson(body, UserShopTypeBean.class);
                    shopCats = bean.getShopCats();
                    menuAdapter.setList(shopCats);
                    if (shopCats != null && shopCats.size() > 0) {
                        loadHomeData(shopCats.get(0).getId(), 1);
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });

    }

    private int page = 1;

    private void loadHomeData(int id, int page) {
        this.currentId = id;
        this.page = page;
        HttpParams params = new HttpParams();
        params.put("catId", id + "");
        params.put("page", page + "");
        params.put("limit", "18");
        params.put("orderby", "1");
        params.put("asc", "2");
        if (latLng != null) {
            params.put("lonlat", latLng.longitude + "," + latLng.latitude);
        }
        if (!TextUtils.isEmpty(SharedPreferencesHelper.getCity())) {
            city = SharedPreferencesHelper.getCity();
        }
        params.put("city", city);

        OkGoUtils.normalRequest(MyUrl.getCatShops, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    CircleShopsListBean bean = GsonUtils.getGson().fromJson(body, CircleShopsListBean.class);
                    if (dataList == null) {
                        dataList = new ArrayList<>();
                    }
                    if (CricleMoreActivity.this.page <= 1) {
                        dataList.clear();
                    }
                    if (bean == null || bean.getData() == null) {
                        return;
                    }
                    if (CricleMoreActivity.this.page > 1 && (bean.getData() == null || bean.getData().size() == 0)) {
                        ToastUtils.showShortToast(CricleMoreActivity.this, "暂无更多数据");
                    } else {
                        dataList.addAll(bean.getData());
                        homeAdapter.setList(dataList);
                    }
                    if (dataList == null || dataList.size() == 0) {
                        tvEmpty.setVisibility(View.VISIBLE);
                    } else {
                        tvEmpty.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.iv_sousuo, R.id.rl_sousuo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_sousuo:
                CommonUtil.startIntent(this, SearchShopsListActivity.class);
                break;
            case R.id.rl_sousuo:
                CommonUtil.startIntent(this, SearchShopsListActivity.class);
                break;
        }
    }


    private LatLng latLng;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private static final int PERMISSION_REQUEST_MY_REQUEST = 3;

    private void loadPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissionList = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_SETTINGS) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.WRITE_SETTINGS);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            if (!permissionList.isEmpty()) {  //申请的集合不为空时，表示有需要申请的权限
                requestPermissions(permissionList.toArray(new String[permissionList.size()]), PERMISSION_REQUEST_MY_REQUEST);
            } else { //所有的权限都已经授权过了
                initLocation();
            }
        } else {
            initLocation();
        }

    }

    /**
     * 如果AMapLocationClient是在当前Activity实例化的，
     * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
        }
    }

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(this);
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000 * 10);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                city = aMapLocation.getCity();
                loadHomeData(currentId, 1);
                mLocationClient.stopLocation();
            }
        } else {
            LogUtils.e("定位失败");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults != null && grantResults.length != 0) {
            if (requestCode == PERMISSION_REQUEST_MY_REQUEST) {
                // 定位权限
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    initLocation();
                } else {
                    com.blankj.utilcode.util.ToastUtils.showShort("没有开启定位权限，定位失败");
                    DialogUtil.openAppDetails(this, "定位");
                }
            }
        }
    }
}
